<template>
  <div class="page">

    <div class="controls-section">
      <div class="filters">
        <div class="filter-item single">
          <button class="btn-primary" @click="openCreate">新建</button>
          <label class="filter-label">收款单ID</label>
          <input class="filter-input" v-model="query.paymentOrderNo" placeholder="输入收款单ID" />
        </div>
      </div>
      <div class="actions">
        <button class="btn-primary" @click="loadData">搜索</button>
        <button class="btn-secondary" @click="resetQuery">重置</button>

      </div>
    </div>

    <div class="table-section">
      <table>
        <thead>
          <tr>
            <th>付款单号</th>
            <th>销售单号</th>
            <th>核销金额</th>
            <th>核销日期</th>
            <th>财务人员</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="row in tableData" :key="row.id">
            <td class="link-style" @click="viewDetail(row)">{{ row.paymentOrderNo }}</td>
            <td>{{ row.relatedSalesOrder || '-' }}</td>
            <td>{{ fmtMoney(row.writeOffAmount) }}</td>
            <td>{{ fmtDateTime(row.writeOffDate) }}</td>
            <td>{{ row.financeUserName || row.uId || '-' }}</td>
          </tr>
        </tbody>
      </table>
    </div>

    <div class="pagination-section">
      <div class="pagination-info">共 {{ pagination.total }} 条记录</div>
      <div class="pagination-controls">
        <button
          :disabled="pagination.current <= 1"
          @click="changePage(pagination.current - 1)"
          class="pagination-btn"
        >
          ‹
        </button>
        <button class="pagination-btn active" disabled>{{ pagination.current }}</button>
        <button
          :disabled="pagination.current >= totalPages"
          @click="changePage(pagination.current + 1)"
          class="pagination-btn"
        >
          ›
        </button>
        <select v-model.number="pagination.size" @change="changePageSize" class="page-size-select">
          <option value="5">5条/页</option>
          <option value="10">10条/页</option>
          <option value="20">20条/页</option>
        </select>
      </div>
    </div>

    <!-- 详情抽屉（对齐收款单样式） -->
    <div class="detail-drawer" :class="{ 'show': detailVisible }">
      <div class="drawer-content" v-if="detail && detail.id">
        <div class="detail-section">
          <h4>基本信息</h4>
          <div class="detail-grid">
            <div class="detail-item"><label>付款单号：</label><span>{{ detail.paymentOrderNo }}</span></div>
            <div class="detail-item"><label>核销单号：</label><span>{{ detail.writeOffNo }}</span></div>
            <div class="detail-item"><label>销售单号：</label><span>{{ detail.relatedSalesOrder || '-' }}</span></div>
          </div>
        </div>

        <div class="detail-section">
          <h4>金额信息</h4>
          <div class="detail-grid">
            <div class="detail-item"><label>核销金额：</label><span class="amount">{{ fmtMoney(detail.writeOffAmount) }}</span></div>
          </div>
        </div>

        <div class="detail-section">
          <h4>其他信息</h4>
          <div class="detail-grid">
            <div class="detail-item"><label>核销日期：</label><span>{{ fmtDateTime(detail.writeOffDate) }}</span></div>
            <div class="detail-item"><label>财务人员：</label><span>{{ detail.financeUserName || detail.uId || '-' }}</span></div>
          </div>
        </div>
      </div>
    </div>

    <!-- 新建付款核销模态框（对齐收款单样式） -->
    <div class="modal-overlay" v-if="createVisible" @click="createVisible=false">
      <div class="create-modal" @click.stop>
        <div class="modal-header">
          <h3>新建付款核销</h3>
          <button class="close-btn" @click="createVisible=false">×</button>
        </div>
        <div class="modal-content">
          <form @submit.prevent="submitCreate">
            <div class="form-grid">

              <div class="form-group">
                <label>核销单号</label>
                <input v-model="createForm.writeOffNo" placeholder="自动生成，保存后显示" readonly />
              </div>

              <div class="form-group">
                <label class="required">付款单ID</label>
                <input type="number" v-model.number="createForm.paymentOrderId" placeholder="请输入付款单ID" required />
              </div>

              <div class="form-group">
                <label class="required">核销金额</label>
                <input type="number" step="0.01" v-model.number="createForm.writeOffAmount" placeholder="请输入核销金额" required />
              </div>

              <div class="form-group">
                <label>核销日期</label>
                <input type="datetime-local" v-model="createForm.writeOffDate" />
              </div>

              <div class="form-group">
                <label>财务人员ID</label>
                <input type="number" v-model.number="createForm.uId" placeholder="请输入财务人员ID" />
              </div>

            </div>

            <div class="form-actions">
              <button type="button" class="btn-secondary" @click="createVisible=false">取消</button>
              <button type="submit" class="btn-primary">保存</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>

</template>

<script>
import { paymentWriteOffPage, paymentWriteOffDetail, paymentWriteOffCreate } from '@/api/finance/paymentWriteOff'

export default {
  name: 'PaymentWriteOff',
  data() {
    return {
      query: { writeOffNo: '', paymentOrderNo: '' },
      pagination: { current: 1, size: 10, total: 0 },
      tableData: [],
      detailVisible: false,
      detail: {},
      createVisible: false,
      createForm: { writeOffNo: '', paymentOrderId: null, writeOffAmount: null, writeOffDate: '', uId: null }
    }
  },
  created() {
    this.loadData()
  },
  computed: {
    totalPages() {
      const pages = Math.ceil((this.pagination.total || 0) / (this.pagination.size || 10))
      return pages > 0 ? pages : 1
    }
  },
  methods: {
    async loadData() {
      const payload = {
        pageNum: this.pagination.current,
        pageSize: this.pagination.size,
        writeOffNo: this.query.writeOffNo || undefined,
        paymentOrderNo: this.query.paymentOrderNo || undefined
      }
      const res = await paymentWriteOffPage(payload)
      const data = res && res.data && res.data.data ? res.data.data : res.data
      this.tableData = (data.records || [])
      this.pagination.total = Number(data.total || 0)
    },
    resetQuery() {
      this.query = { writeOffNo: '', paymentOrderNo: '' }
      this.pagination.current = 1
      this.loadData()
    },
    changePage(page) {
      if (page < 1 || page > this.totalPages) return
      this.pagination.current = page
      this.loadData()
    },
    changePageSize() {
      this.pagination.current = 1
      this.loadData()
    },
    async viewDetail(row) {
      const res = await paymentWriteOffDetail(row.id)
      const data = res && res.data && res.data.data ? res.data.data : res.data
      this.detail = data || {}
      this.detailVisible = true
    },
    async submitCreate() {
      const payload = { ...this.createForm }
      // 可留空，后端自动生成
      if (!payload.writeOffNo) delete payload.writeOffNo
      // 数值转 number
      if (payload.paymentOrderId != null) payload.paymentOrderId = Number(payload.paymentOrderId)
      if (payload.writeOffAmount != null) payload.writeOffAmount = Number(payload.writeOffAmount)
      if (payload.uId != null && payload.uId !== '') payload.uId = Number(payload.uId); else delete payload.uId
      // 使用 ISO8601，后端默认可解析
      if (payload.writeOffDate) {
        try {
          const raw = payload.writeOffDate
          const iso = (function toISO(v) {
            if (typeof v === 'string') {
              const s = v.includes('T') ? v : v.replace(' ', 'T')
              const d = new Date(s)
              return d.toISOString()
            }
            const d = new Date(v)
            return d.toISOString()
          })(raw)
          payload.writeOffDate = iso
        } catch(e) {
          // 兜底：移除不可解析的日期，交给后端默认
          delete payload.writeOffDate
        }
      } else {
        delete payload.writeOffDate
      }
      try {
        await paymentWriteOffCreate(payload)
        this.createVisible = false
        this.loadData()
      } catch (e) {
        console.error('创建付款核销失败', e)
      }
    },
    openCreate() {
      this.createVisible = true
      this.createForm = { writeOffNo: '', paymentOrderId: null, writeOffAmount: null, writeOffDate: '', uId: null }
    },
    fmtMoney(v) {
      if (v === null || v === undefined) return '-'
      const n = Number(v)
      if (Number.isNaN(n)) return '-'
      return n.toFixed(2)
    },
    fmtDateTime(v) {
      if (!v) return '-'
      const d = new Date(v)
      if (Number.isNaN(d.getTime())) return '-'
      const pad = n => String(n).padStart(2, '0')
      return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
    },
    // 将 <input type="datetime-local"> 的值格式化给后端
    formatDateTimeForBackend(localVal) {
      try {
        // localVal 形如 '2025-09-04T10:30'
        if (typeof localVal === 'string' && localVal.includes('T')) {
          const [date, time] = localVal.split('T')
          const hhmmss = time && time.length === 5 ? `${time}:00` : (time || '00:00:00')
          return `${date} ${hhmmss}`
        }
        // 兼容直接传 Date 或时间戳
        const d = new Date(localVal)
        const pad = n => String(n).padStart(2, '0')
        return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
      } catch(e) {
        return localVal
      }
    }
  }
}
</script>

<style scoped>
.page { padding: 20px; background: #f5f7fa; }
.title-section { display:flex; justify-content:space-between; align-items:center; margin-bottom:16px; }
.controls-section { display:flex; justify-content:space-between; gap:16px; background:#fff; padding:16px; border-radius:8px; margin-bottom:16px; }
.filters { display:flex; gap:16px; align-items:center; }
.filter-item { display:flex; gap:8px; align-items:center; }
.filter-item.single { min-width: 360px; }
.filter-label { font-size:14px; color:#303133; }
.filter-input { padding:8px 10px; border:1px solid #dcdfe6; border-radius:4px; width:220px; }
.actions { display:flex; gap:10px; }
.btn-primary { background:#409eff; color:#fff; border:none; padding:8px 16px; border-radius:4px; cursor:pointer; }
.btn-secondary { background:#fff; color:#606266; border:1px solid #dcdfe6; padding:8px 16px; border-radius:4px; cursor:pointer; }
.table-section { background:#fff; padding:16px; border-radius:8px; }
table { width:100%; border-collapse:collapse; }
th, td { padding:10px; border-bottom:1px solid #ebeef5; text-align:left; }
.pagination-section { background:#fff; padding:20px; border-radius:8px; display:flex; justify-content:space-between; align-items:center; }
.pagination-info { color:#606266; font-size:14px; }
.pagination-controls { display:flex; align-items:center; gap:8px; }
.pagination-btn { padding:6px 12px; border:1px solid #dcdfe6; background:#fff; cursor:pointer; border-radius:4px; min-width:40px; }
.pagination-btn:hover:not(:disabled) { border-color:#409eff; color:#409eff; }
.pagination-btn.active { background:#409eff; color:#fff; border-color:#409eff; }
.pagination-btn:disabled { cursor:not-allowed; opacity:0.6; }
.page-size-select { padding:6px; border:1px solid #dcdfe6; border-radius:4px; }
.link-style { color:#409eff; cursor:pointer; }

/* 简易抽屉与模态 */
.drawer { position:fixed; top:0; right:0; bottom:0; left:0; background:rgba(0,0,0,.35); display:flex; justify-content:flex-end; }
.drawer-inner { width:420px; background:#fff; height:100%; display:flex; flex-direction:column; }
.drawer-header { padding:12px 16px; border-bottom:1px solid #ebeef5; display:flex; justify-content:space-between; }
.drawer-body { padding:16px; overflow:auto; }
.close { cursor:pointer; }

/* 新建模态框样式（与收款单一致） */
.modal-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.5); display: flex; justify-content: center; align-items: center; z-index: 1001; }
.create-modal { background-color: #fff; border-radius: 8px; width: 760px; max-height: 80vh; overflow-y: auto; }
.modal-header { padding: 16px 20px; border-bottom: 1px solid #ebeef5; display: flex; justify-content: space-between; align-items: center; background: #8ec7ff; color: #fff; border-radius: 8px 8px 0 0; }
.modal-header h3 { margin: 0; font-size: 18px; font-weight: 600; }
.modal-content { padding: 20px; }
.close-btn { background: none; border: none; font-size: 24px; cursor: pointer; color: #fff; }
.close-btn:hover { color: #eef5ff; }
.form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 16px 20px; margin-bottom: 24px; }
.form-group { display: flex; flex-direction: column; gap: 8px; }
.form-group label { font-weight: 500; color: #303133; }
.form-group label.required::after { content: ' *'; color: #f56c6c; }
.form-group input, .form-group select { padding: 8px 12px; border: 1px solid #dcdfe6; border-radius: 4px; font-size: 14px; height: 36px; }
.form-group input:focus, .form-group select:focus { outline: none; border-color: #409eff; }
.form-actions { display: flex; justify-content: flex-end; gap: 12px; padding-top: 20px; border-top: 1px solid #ebeef5; }
</style>


